package com.itheima.filter;

import com.google.gson.Gson;
import com.itheima.util.JwtUtils;
import com.itheima.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    @Autowired
    private Gson gson;


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1. 将请求和响应强制转换为HTTP的
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //2. 获取请求uri
        String uri = request.getRequestURI();
        log.info("请求路径{}",uri);
        //3. 判断uri是否为/login，如果包含，说明是登录操作，放行
        if(uri.equals("/login")){
            filterChain.doFilter(servletRequest,servletResponse);
            return;//结束判断
        }
        //4.获取请求头中的令牌(token)解析后，如果解析失败，返回错误结果
        String token = request.getHeader("token");
        try {

            JwtUtils.parseJWT(token);
        }catch (Exception e){
            log.info("token错误");
            //返回错误信息
            String json = gson.toJson(Result.error("NOT_LOGIN"));
            response.setContentType("application/json'charset=utf-8");
            response.getWriter().write(json);
            return;
        }

        //5.放行
        filterChain.doFilter(request,response);
    }
}
